package io.renren.modules.api.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.naming.NoNameCoder;
import com.thoughtworks.xstream.io.xml.StaxDriver;
import io.renren.common.exception.RRException;
import io.renren.common.utils.PayUtils.AliPay.AliPayUtil;
import io.renren.common.utils.PayUtils.AliPay.AlipayNotify;
import io.renren.common.utils.PayUtils.WxPay.weixin.SignValidateUtil;
import io.renren.common.utils.PayUtils.WxPay.weixin.util.ConstantUtil;
import io.renren.common.utils.PayUtils.WxPay.weixin.util.WXUtil;
import io.renren.common.utils.QmSendPush;
import io.renren.modules.api.entity.PsCouponEntity;
import io.renren.modules.api.service.IPayService;
import io.renren.modules.api.service.PsCouponService;
import io.renren.modules.driver.entity.PsParamSetEntity;
import io.renren.modules.driver.entity.SjDriverEntity;
import io.renren.modules.driver.service.PsParamSetService;
import io.renren.modules.driver.service.SjDriverService;
import io.renren.modules.psfinancemanage.entity.PsDriverStatisticsEntity;
import io.renren.modules.psfinancemanage.service.PsDriverStatisticsService;
import io.renren.modules.psorder.entity.PsOrderEntity;
import io.renren.modules.psorder.service.PsOrderService;
import io.renren.modules.shop.controller.front.pay.Signature;
import io.renren.modules.shop.controller.front.pay.Util;
import io.renren.modules.shop.controller.front.pay.WxPlaceOrder;
import io.renren.modules.shop.controller.front.pay.XMLParser;
import io.renren.modules.shop.util.AlipayConfig;
import io.renren.modules.shop.util.CommondUtil;
import io.renren.modules.shop.util.Configure;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by WDJ on 2017/12/15.
 */
@Service("payService")
public class PayServiceImpl implements IPayService {

    private Logger logger = Logger.getLogger(PayServiceImpl.class);

    @Autowired
    private PsOrderService psOrderService;
    @Autowired
    private PsCouponService psCouponService;
    @Autowired
    private SjDriverService driverService;
    @Autowired
    private PsDriverStatisticsService psDriverStatisticsService;
    @Autowired
    private PsParamSetService psParamSetService;

    @Override
    public String appAliPayPsOrder(String orderNum,Long couponid) {
        String orderString = "";
        PsOrderEntity psOrder = psOrderService.queryByOrderNum(orderNum);//要支付的订单
        if (psOrder == null) {
            throw new RRException("订单不存在!",-1);
        }
        BigDecimal payMoney = new BigDecimal("0");
        if ( couponid != null ){
            PsCouponEntity psCoupon = psCouponService.queryObject(couponid);
            if ( psCoupon.getEndTime() != null && psCoupon.getEndTime().getTime() < new Date().getTime() ){  //优惠券过期
                throw new RRException("优惠券过期了!",-3);
            }
            if ( psCoupon.getConditionPrice() != null && psCoupon.getConditionPrice().compareTo(psOrder.getTotalPrice()) == 1 ) {
                throw new RRException("使用价格不满足优惠券条件",-4);
            }
            //使用优惠券id存在订单里
            psOrder.setPsCouponId(psCoupon.getId());
            psOrderService.update(psOrder);
            payMoney = psOrder.getTotalPrice().subtract(psCoupon.getPrice());
        } else {
            payMoney = psOrder.getTotalPrice();
        }

        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.URL, AlipayConfig.APPID,
                AlipayConfig.RSA_PRIVATE_KEY, AlipayConfig.FORMAT, AlipayConfig.CHARSET,
                AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.SIGNTYPE);
        //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        //SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
        model.setBody("从"+psOrder.getStartName()+"到"+psOrder.getEndName());
        model.setSubject("千万家城市配送订单");
        model.setOutTradeNo(orderNum);
        model.setTimeoutExpress("30m");
        model.setTotalAmount(payMoney.toString()); //真实价格
//        model.setTotalAmount("0.01"); //测试价格
        model.setProductCode("QWJ_APP_PAY");

        request.setBizModel(model);
        request.setNotifyUrl(AlipayConfig.notify_url); //商户外网可以访问的异步地址
        try {
            //这里和普通的接口调用不同，使用的是sdkExecute
            AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
            orderString = response.getBody();
        } catch (AlipayApiException e) {
            throw new RRException("支付发生异常请重试!");
        }
        return orderString;

    }

    @Override
    public String appAliPayPsOrderOld(String orderNum,Long couponid) {
        String orderString = "";
        PsOrderEntity psOrder = psOrderService.queryByOrderNum(orderNum);//要支付的订单
        if (psOrder == null) {
            throw new RRException("订单不存在!",-1);
        }
        BigDecimal payMoney = new BigDecimal("0");
        if ( couponid != null ){
            PsCouponEntity psCoupon = psCouponService.queryObject(couponid);
            if ( psCoupon.getEndTime() != null && psCoupon.getEndTime().getTime() < new Date().getTime() ){  //优惠券过期
                throw new RRException("优惠券过期了!",-3);
            }
            if ( psCoupon.getConditionPrice() != null && psCoupon.getConditionPrice().compareTo(psOrder.getTotalPrice()) == 1 ) {
                throw new RRException("使用价格不满足优惠券条件",-4);
            }
            //使用优惠券id存在订单里
            psOrder.setPsCouponId(psCoupon.getId());
            psOrderService.update(psOrder);
            payMoney = psOrder.getTotalPrice().subtract(psCoupon.getPrice());
        } else {
            payMoney = psOrder.getTotalPrice();
        }

        String body = "从"+psOrder.getStartName()+"到"+psOrder.getEndName();
        // 真实价格 payMoney.toString()
        orderString = AliPayUtil.getAliSignOrder("千万家城市配送订单", body,"0.01",
                psOrder.getOrdernum());
        return orderString;
    }

    @Override
    public void aliPayPsOrderNotify(HttpServletResponse response, HttpServletRequest request) throws Exception {
        logger.info("支付宝回调开始...");
        PrintWriter out = response.getWriter();

        // 获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
            // valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
            params.put(name, valueStr);
        }
        // 获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//

        // 商户订单号
        String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
        // 支付宝交易号
        String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
        // 交易状态
        String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");
        //付款金额
        String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");
        // 获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//
        // 计算得出通知验证结果
        // boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String
        // publicKey, String charset, String sign_type)
        boolean verify_result = AlipaySignature.rsaCheckV1(params, AlipayConfig.ALIPAY_PUBLIC_KEY,
                AlipayConfig.CHARSET, "RSA2");

        if (verify_result) {// 验证成功
            // ////////////////////////////////////////////////////////////////////////////////////////
            // 请在这里加上商户的业务逻辑程序代码

            // ——请根据您的业务逻辑来编写程序（以下代码仅作参考）——

            if (trade_status.equals("TRADE_FINISHED")) {
                // 判断该笔订单是否在商户网站中已经做过处理
                // 如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                // 请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
                // 如果有做过处理，不执行商户的业务程序

                // 注意：
                // 如果签约的是可退款协议，退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
                // 如果没有签约可退款协议，那么付款完成后，支付宝系统发送该交易状态通知。
            } else if (trade_status.equals("TRADE_SUCCESS")) {
                // 判断该笔订单是否在商户网站中已经做过处理
                // 如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                // 请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
                // 如果有做过处理，不执行商户的业务程序
                // 注意：
                // 如果签约的是可退款协议，那么付款完成后，支付宝系统发送该交易状态通知。
                // 支付交易成功
                PsOrderEntity psOrder = psOrderService.queryByOrderNum(out_trade_no);//支付的订单
                if ("0".equals(psOrder.getPayStatus())) {   //订单未做过处理
                    psOrder.setPayStatus("1");              //更新订单 为支付成功
                    psOrder.setOrderStatus("2");            //订单状态为已支付
                    psOrder.setPayTime(new Date());         //完成支付时间
                    psOrder.setPayType("alipay");           //支付方式为支付宝支付
                    psOrder.setPayOrder(trade_no);          //设置支付宝支付订单号
                    psOrder.setPayRealymoney(Double.parseDouble(total_amount));
                    psOrderService.update(psOrder);

                    updateOrAddDriverStatistics(psOrder,"alipay");

                    SjDriverEntity driver = driverService.queryObject(psOrder.getDriverId());

                    //推送司机订单已支付成功
                    QmSendPush.sendAlreadyPayToDriver(driver.getRegistrationId(),psOrder);

                }

            }
            // ////////////////////////////////////////////////////////////////////////////////////////
            out.println("success");    //请不要修改或删除
            out.flush();
            out.close();
        } else {// 验证失败
            logger.info("========支付宝异步通知回调签名失败=======");
            out.println("fail");
            out.flush();
            out.close();
        }
        logger.info("支付宝回调结束...");
    }

    /**
     * 更新或者添加司机司机收入统计
     * @param psOrder 订单实体
     */
    @Override
    public void updateOrAddDriverStatistics(PsOrderEntity psOrder,String payType){
        //更新或者新增司机收入统计表 暂以订单金额统计
        PsDriverStatisticsEntity psDriverStatistics = psDriverStatisticsService.queryByDriverId(psOrder.getDriverId());
        PsParamSetEntity psParamSet = psParamSetService.queryObject((long)1); //获取当前平台抽成比例
        if ( psDriverStatistics == null) {  //没有此条司机统计记录
            PsDriverStatisticsEntity psDriverStatisticsNew = new PsDriverStatisticsEntity();
            psDriverStatisticsNew.setDriverId(psOrder.getDriverId());    //司机id
            psDriverStatisticsNew.setDriverName(psOrder.getDriverName());//司机姓名
            psDriverStatisticsNew.setCarStyle(psOrder.getVehicleType()); //车型
            if ("alipay".equals(payType)) {
                psDriverStatisticsNew.setAliIncome(psOrder.getTotalPrice()); //支付宝收入
            } else if ("wxpay".equals(payType)){
                psDriverStatisticsNew.setWxIncome(psOrder.getTotalPrice());  //微信收入
            } else if("cash".equals(payType)){
                psDriverStatisticsNew.setCaseIncome(psOrder.getTotalPrice()); //现金收入
            }
            psDriverStatisticsNew.setSumIncome(psOrder.getTotalPrice()); //总收入
            psDriverStatisticsNew.setPlatformIncome(psOrder.getTotalPrice().multiply(psParamSet.getParaValue())); //平台收入
            psDriverStatisticsNew.setBalance(psOrder.getTotalPrice().subtract(psDriverStatisticsNew.getPlatformIncome())); //余额
            psDriverStatisticsNew.setWithdrawable(psDriverStatisticsNew.getBalance()); //可提现
            psDriverStatisticsService.save(psDriverStatisticsNew);
        } else {   //有这条统计记录那就更新
            if ("alipay".equals(payType)) {
                psDriverStatistics.setAliIncome(psDriverStatistics.getAliIncome().add(psOrder.getTotalPrice())); //支付宝收入累加
            } else if ("wxpay".equals(payType)){
                psDriverStatistics.setWxIncome(psDriverStatistics.getWxIncome().add(psOrder.getTotalPrice()));   //微信收入累加
            } else if("cash".equals(payType)){
                psDriverStatistics.setCaseIncome(psDriverStatistics.getCaseIncome().add(psOrder.getTotalPrice())); //现金累加
            }
            psDriverStatistics.setSumIncome(psDriverStatistics.getSumIncome().add(psOrder.getTotalPrice()));     //总收入累加
            //平台收入
            psDriverStatistics.setPlatformIncome(psDriverStatistics.getPlatformIncome().add(psOrder.getTotalPrice().multiply(psParamSet.getParaValue())));
            BigDecimal pureIncome = psOrder.getTotalPrice().subtract( psOrder.getTotalPrice().multiply(psParamSet.getParaValue())); //除去抽成纯收入
            psDriverStatistics.setBalance(psDriverStatistics.getBalance().add(pureIncome));                 //余额累加
            psDriverStatistics.setWithdrawable(psDriverStatistics.getWithdrawable().add(pureIncome));       //可提现累加
            psDriverStatisticsService.update(psDriverStatistics);

        }

    }

    @Override
    public void aliPayPsOrderNotifyOld(HttpServletResponse response, HttpServletRequest request) throws Exception {
        logger.info("支付宝回调开始...");
        PrintWriter out = response.getWriter();

        //获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
            params.put(name, valueStr);
        }
        //交易状态
        String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");
        //商家订单号
        String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
        //支付宝订单号
        String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
        //付款金额
        String total_fee = new String(request.getParameter("total_fee").getBytes("ISO-8859-1"), "UTF-8");
//        System.out.println("回调MAP" + params);
//获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//
//        String notify_time = new String(request.getParameter("notify_time").getBytes("ISO-8859-1"), "UTF-8");
        if (AlipayNotify.verify(params)) {//验证成功

            if (trade_status.equals("TRADE_FINISHED")) {

            } else if (trade_status.equals("TRADE_SUCCESS")) {

                // 支付交易成功
                PsOrderEntity psOrder = psOrderService.queryByOrderNum(out_trade_no);//支付的订单
                psOrder.setPayStatus("1");              //更新订单 为支付成功
                psOrder.setOrderStatus("2");            //订单状态为已支付
                psOrder.setPayTime(new Date());         //完成支付时间
                psOrder.setPayType("alipay");           //支付方式为支付宝支付
                psOrder.setPayOrder(trade_no);          //设置支付宝支付订单号
                psOrder.setPayRealymoney(Double.parseDouble(total_fee));
                psOrderService.update(psOrder);

                logger.info("========支付宝支付快车通知回调一切OK=======");
            }
                out.println("success");    //请不要修改或删除
                out.flush();
                out.close();
        } else {//验证失败
            logger.info("========支付宝异步通知回调签名失败=======");
            out.println("fail");
            out.flush();
            out.close();
        }

    }

    @Override
    public Map<String, Object> appWxPayPsOrder(String orderNum,HttpServletRequest request,
                                               HttpServletResponse response) {
        Map<String, Object> returnMap = new ConcurrentHashMap();

        PsOrderEntity psOrder = psOrderService.queryByOrderNum(orderNum);//要支付的订单
        int totalPrice = 0;

        //拼统一下单接口，9个实际参数+sign
        WxPlaceOrder wxPlaceOrder = new WxPlaceOrder();
        wxPlaceOrder.setAppid(Configure.APP_ID);                                        //应用ID
        wxPlaceOrder.setMch_id(Configure.PAY_ID);                                       //商户号
        wxPlaceOrder.setNonce_str(Util.uuid());                                         //随机字符串
        wxPlaceOrder.setBody("千万家支付中心");                                         //商品描述
        wxPlaceOrder.setDetail("用户" + psOrder.getUserPhone() + "支付订单");           //商品详情
        wxPlaceOrder.setOut_trade_no(orderNum);				                            //商户订单号
        wxPlaceOrder.setTotal_fee(1);							                        //订单总金额，单位为分,1分钱测试
//        wxPlaceOrder.setTotal_fee((int)(psOrder.getPayRealymoney()*100));		        //订单总金额，单位为分
        wxPlaceOrder.setSpbill_create_ip(request.getRemoteAddr()); 		                //终端IP
        wxPlaceOrder.setNotify_url(Configure.NOTIFY_URL);		                        //通知地址
        wxPlaceOrder.setTrade_type("APP");					                            //交易类型
        wxPlaceOrder.setSign(Signature.getSign(wxPlaceOrder));                          //sign
        XStream xStream = new XStream(new StaxDriver(new NoNameCoder()));
        xStream.alias("xml", WxPlaceOrder.class);
        String xml = xStream.toXML(wxPlaceOrder);
        String result = CommondUtil.httpsRequest(Configure.WX_PlACE_ORDER,
                "GET", xml);
        if (!"".equals(result)) {
                    try {
                        Map<String, Object> mapTemp = XMLParser.getMapFromXML(result);
                        if (mapTemp.containsKey("prepay_id")) {
                            // 统一下单接口成功
                            String prepay_id = (String) mapTemp.get("prepay_id");
                            // 签名 并返回前端
                            wxPlaceOrder = new WxPlaceOrder();
                            wxPlaceOrder.setAppid(Configure.APP_ID);
                            wxPlaceOrder.setNonce_str(Util.uuid());
                            wxPlaceOrder.setTimeStamp(System.currentTimeMillis() / 1000+"");
                            wxPlaceOrder.setPrepay_id(prepay_id);

                            returnMap.put("appid", Configure.APP_ID);
                            returnMap.put("partnerid", Configure.PAY_ID);
                            returnMap.put("prepayid", prepay_id);
                            returnMap.put("package", "Sign=WXPay");
                            returnMap.put("noncestr", wxPlaceOrder.getNonce_str());
                            returnMap.put("timestamp", wxPlaceOrder.getTimeStamp());
                            returnMap.put("sign", Signature.getSignPay(wxPlaceOrder));

                }
            } catch (Exception e) {
                throw new RRException("统一下单异常!");
            }
        } else {
            throw new RRException("统一下单访问失败");
        }

        return returnMap;
    }
    @Override
    @Transactional
    public Map<String, Object> appWxPayPsOrderOld(String orderNum,Long couponid,HttpServletRequest request,
                                                  HttpServletResponse response) throws Exception {
        PsOrderEntity psOrder = psOrderService.queryByOrderNum(orderNum);//要支付的订单
        if (psOrder == null) {
            throw new RRException("订单不存在!",-1);
        }
        BigDecimal payMoney = new BigDecimal("0");
        if ( couponid != null ){
            PsCouponEntity psCoupon = psCouponService.queryObject(couponid);
            if ( psCoupon.getEndTime() != null && psCoupon.getEndTime().getTime() < new Date().getTime() ){  //优惠券过期
                throw new RRException("优惠券过期了!",-3);
            }
            if ( psCoupon.getConditionPrice() != null && psCoupon.getConditionPrice().compareTo(psOrder.getTotalPrice()) == 1 ) {
                throw new RRException("使用价格不满足优惠券条件",-4);
            }
            //使用优惠券id存在订单里
            psOrder.setPsCouponId(psCoupon.getId());
            psOrderService.update(psOrder);
            payMoney = psOrder.getTotalPrice().subtract(psCoupon.getPrice());
        } else {
            payMoney = psOrder.getTotalPrice();
        }
        String body = "千万家支付中心测试";//商品描述
        String detail = "用户"+psOrder.getUserName()+"支付配送订单";//商品详情
        String total_fee = payMoney.multiply(new BigDecimal("100")).toString();//真实总金额 单位:分
//        String total_fee = "1";//测试总金额 单位:分
        String out_trade_no = orderNum;//商户订单号
        Map<String, Object> resInfo = WXUtil.getResInf(body, detail, total_fee, out_trade_no, request, response);

        return resInfo;
    }

    @Override
    public void wxPayPsOrderNotify(HttpServletResponse response, HttpServletRequest request) throws Exception {
        logger.info("微信支付回调开始...");
        Map<String, String> map = parseXml(request);
        WxPlaceOrder wxPlaceOrder = new WxPlaceOrder();
        // 当前订单的通知业务
        if ("SUCCESS".equals(map.get("return_code"))) {
            if ("SUCCESS".equals(map.get("result_code"))) {
                String orderNum = map.get("out_trade_no");
                String transaction_id = map.get("transaction_id");
                // 支付交易成功
                PsOrderEntity psOrder = psOrderService.queryByOrderNum(orderNum);//支付的订单
                psOrder.setPayStatus("1");              //更新订单 为支付成功
                psOrder.setOrderStatus("2");            //订单状态为已支付
                psOrder.setPayTime(new Date());         //完成支付时间
                psOrder.setPayType("wxpay");               //支付方式为wx支付
                psOrder.setPayOrder(transaction_id);    //设置微信支付订单号
                psOrderService.update(psOrder);

            }
            // 通知成功
            wxPlaceOrder.setReturn_code("SUCCESS");
            XStream xStream = new XStream(new StaxDriver(new NoNameCoder()));
            xStream.alias("xml", WxPlaceOrder.class);
            String returnXml = xStream.toXML(wxPlaceOrder);
            try {
                response.getWriter().write(returnXml);
            } catch (IOException e) {
                logger.info("通知回调 微信服务器 异常", e);
            }
        }
        logger.info("微信支付回调结束...");

    }

    public Map<String, String> parseXml(HttpServletRequest request)
            throws Exception {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse(request.getInputStream());
        // 获取到document里面的全部结点
        NodeList allNodes = document.getFirstChild().getChildNodes();
        Node node;
        Map<String, String> map = new HashMap<String, String>();
        int i = 0;
        while (i < allNodes.getLength()) {
            node = allNodes.item(i);
            if (node instanceof Element) {
                map.put(node.getNodeName(), node.getTextContent());
            }
            i++;
        }
        return map;
    }

    @Override
    public void wxPayPsOrderNotifyOld(HttpServletResponse response, HttpServletRequest request) throws Exception {
        PrintWriter out = response.getWriter();
        StringBuilder result = new StringBuilder();
        try {
            String line;
            BufferedReader reader = request.getReader();
            while (null != (line = reader.readLine())) {
                result.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        String rxml = result.toString();

        //商户号
        String partner = ConstantUtil.PARTNER;
        //密钥
        String key = ConstantUtil.WX_API_KEY;

        //判断签名
        if (SignValidateUtil.checkIsSignValidFromResponseString(rxml)) {
            //xml转map
            SortedMap<String, Object> map = SignValidateUtil.doXMLParse(rxml);
            // 当前订单的通知业务
            WxPlaceOrder wxPlaceOrder = new WxPlaceOrder();
            if ("SUCCESS".equals(map.get("return_code"))) {
                if ("SUCCESS".equals(map.get("result_code"))) {
                    String orderNum = map.get("out_trade_no").toString();
                    String transaction_id = map.get("transaction_id").toString();
                    //总金额
                    String total_fee = map.get("total_fee").toString();
                    double total_fee_double = Integer.parseInt(total_fee) / 100.0;
                    // 支付交易成功
                    PsOrderEntity psOrder = psOrderService.queryByOrderNum(orderNum);//支付的订单
                    if ("0".equals(psOrder.getPayStatus())) {   //订单未做过处理,已处理就不修改业务数据重要
                        psOrder.setPayStatus("1");              //更新订单 为支付成功
                        psOrder.setOrderStatus("2");            //订单状态为已支付
                        psOrder.setPayTime(new Date());         //完成支付时间
                        psOrder.setPayType("wxpay");               //支付方式为wx支付
                        psOrder.setPayOrder(transaction_id);    //设置微信支付订单号
                        psOrder.setPayRealymoney(total_fee_double);
                        psOrderService.update(psOrder);

                        updateOrAddDriverStatistics(psOrder,"wxpay");

                        SjDriverEntity driver = driverService.queryObject(psOrder.getDriverId());

                        //推送司机订单已支付成功
                        QmSendPush.sendAlreadyPayToDriver(driver.getRegistrationId(),psOrder);

                    }

                }
                // 通知成功
                wxPlaceOrder.setReturn_code("SUCCESS");
                XStream xStream = new XStream(new StaxDriver(new NoNameCoder()));
                xStream.alias("xml", WxPlaceOrder.class);
                String returnXml = xStream.toXML(wxPlaceOrder);
                try {
                    response.getWriter().write(returnXml);
                } catch (IOException e) {
                    logger.info("通知回调 微信服务器 异常", e);
                }
            }
//            //商户订单号
//            String out_trade_no = map.get("out_trade_no").toString();
//            //总金额
//            String total_fee = map.get("total_fee").toString();
//            float total_fee_float = (float) (Integer.parseInt(total_fee) / 100.0);
//            //微信支付订单号
//            String transaction_id = map.get("transaction_id").toString();
            //String time_end = map.get("time_end").toString();
            //订单号前两位

//                logger.info("========微信通知回调一切OK=======");
//                String s = "<xml>\n" +
//                        "  <return_code><![CDATA[SUCCESS]]></return_code>\n" +
//                        "  <return_msg><![CDATA[OK]]></return_msg>\n" +
//                        "</xml>";
//                out.println(s);
//                out.flush();
//                out.close();

        } else {
            logger.info("微信异步通知签名验证失败");
            String s = "<xml>\n" +
                    "  <return_code><![CDATA[FAIL]]></return_code>\n" +
                    "  <return_msg><![CDATA[签名验证失败]]></return_msg>\n" +
                    "</xml>";
            out.println(s);
            out.flush();
            out.close();
        }

    }




}
